package yolorpc;


import lombok.extern.slf4j.Slf4j;
import yolorpc.config.RpcConfig;
import yolorpc.constant.RpcConstant;
import yolorpc.registry.Registry;
import yolorpc.registry.RegistryConfig;
import yolorpc.registry.RegistryFactory;
import yolorpc.utils.ConfigUtils;

/**
 * @author yolo
 * @Program RPC
 * @description RPC框架应用，相当于holder，存放了全局使用的变量。双检锁单例模式实现
 * @create 2025-04-24 13:59
 **/
@Slf4j
public class RpcApplication {
    public static volatile RpcConfig rpcConfig;

    /**
     * @descript 框架初始化
     * @author yolo
     * @date 2025/4/24 14:03
     * @param newRpcConfig
     * @return void
     **/
    private static void init(RpcConfig newRpcConfig){
        rpcConfig = newRpcConfig;
        log.info("rpc init, config = {}", newRpcConfig.toString());
        // 注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        log.info("registry init, config = {}", registryConfig);

        // 创建并注册 Shutdown Hook，JVM 退出时执行操作
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    /**
     * @descript
     * @author yolo
     * @date 2025/4/24 14:06
     * @param
     * @return void
     **/
    public static void init(){
        RpcConfig newRpcConfig;
        try {
            newRpcConfig = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_CONSTANT_PREFIX);
        } catch (Exception e){
            // 配置加载失败，加载默认配置
            newRpcConfig = new RpcConfig();
        }
        init(newRpcConfig);
    }

    public static RpcConfig getRpcConfig(){
        if (rpcConfig == null){
            synchronized (RpcApplication.class){
                if (rpcConfig == null){
                    init();
                }
            }
        }
        return rpcConfig;
    }
}
